package db

import (
	"database/sql"
	"encoding/json"
	_ "github.com/mattn/go-sqlite3"
	"path"
)

const (
	createDndTable = `
CREATE TABLE IF NOT EXISTS "dndRi"
(
    "groupId" INTEGER PRIMARY KEY ,
    "json" TEXT NOT NULL 
);
`
	upsertDndTable = `
INSERT OR
REPLACE
INTO dndRi (groupId, json)
VALUES (?, ?)
`
	selectDndTable = `
SELECT json
FROM "dndRi"
where groupId = ?;
`

	deleteDndTable = `
DELETE
FROM dndRi
WHERE groupId = ?;
`
)

type MapSorter []Item

type Item struct {
	Key string
	Val int64
}

func NewMapSorter(m map[string]int64) MapSorter {
	ms := make(MapSorter, 0, len(m))
	for k, v := range m {
		ms = append(ms, Item{k, v})
	}
	return ms
}

func (r MapSorter) Len() int {
	return len(r)
}

func (r MapSorter) Less(i, j int) bool {
	return r[i].Val > r[j].Val
}

func (r MapSorter) Swap(i, j int) {
	r[i], r[j] = r[j], r[i]
}

var dndDb *sql.DB

func init() {
	dndDb, _ = sql.Open("sqlite3", path.Join(getExecutePath(), "dnd.db"))
}

func CreateDndDb() {
	_, _ = dndDb.Exec(createDndTable)
}

func SelectDndDb(groupId int64) (result map[string]int64) {
	rows, err := dndDb.Query(selectDndTable, groupId)
	if err != nil {
		return make(map[string]int64)
	}
	for rows.Next() {
		var mapString string
		_ = rows.Scan(&mapString)
		_ = json.Unmarshal([]byte(mapString), &result)
	}
	return
}

func UpsertDndDb(groupId int64, mapInput map[string]int64) {
	result := SelectDndDb(groupId)
	if result == nil {
		result = make(map[string]int64)
	}
	for k, v := range mapInput {
		result[k] = v
	}
	jsonString, _ := json.Marshal(result)
	stmt, _ := dndDb.Prepare(upsertDndTable)
	_, _ = stmt.Exec(groupId, jsonString)
}

func DeleteDndDb(groupId int64) {
	stmt, _ := dndDb.Prepare(deleteDndTable)
	_, _ = stmt.Exec(groupId)
}
